<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
<el-dialog :title="diglogTile" :visible.sync="exaDialogVisible" width="58%" :modal="false" :before-close="handleClose">
		<!-- 新增 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 -->
					<el-form ref="form" :model="addForm" label-width="80px" size="mini">
					<el-row :gutter="20">
						  <el-col :span="val.spanRows" type="flex" v-for="(val,i) in formType" :key="i">
							  <!-- input -->
							  <el-form-item v-if="val.type == 'input'" :label="val.label">
								<el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
							  </el-form-item>
							  <!-- select -->
							  <el-form-item v-if="val.type == 'select'" :label="val.label">
								<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" :disabled="val.disabled">
									<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
									<span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
								</el-select>
							  </el-form-item>
							  <!-- date -->
							  <el-form-item v-if="val.type == 'date'" :label="val.label">
								<el-date-picker class="autoWidth" @focus="testDate(val,i)" @change="changDate"
								type="date" placeholder="选择日期" v-model="$data.addForm[val.modelValue]" :disabled="val.disabled"></el-date-picker>
							  </el-form-item>
							  <!-- btn -->
							  <el-form-item v-if="val.type == 'btn'">
								<el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
							  </el-form-item>
							  <!-- textarea -->
							  <el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
							  	<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="$data.addForm[val.modelValue]" :disabled="val.disabled"></el-input>
							  </el-form-item>
						  </el-col>
						</el-row>
					</el-form>
					<!-- table -->
					<div class="table">
						<el-divider content-position="left">明细数据表:</el-divider>
						<el-table :data="tableData" border @row-dblclick="handledbRow">
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
						</el-table>
						<div class="total">
							<span>合计金额：</span><el-input v-model="totalAmt" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						</div>
					</div>
				</div>
			</div>
			<!-- 提交 -->
			<div v-if="diglogTile === '草稿'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="Submit">确定提交</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 审核 -->
			<div v-if="diglogTile === '审核'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refuseExamine">拒绝审核</el-button>
				<el-button size="mini" type="primary" @click="exaSubmit">确定审核</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 过单 -->
			<div v-if="diglogTile === '过单'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refusePassOrder">拒绝过单</el-button>
				<el-button size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 查看 -->
			<div v-if="diglogTile === '查看药品采购计划' || diglogTile.includes('打印')" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="dy">打印</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">关闭</el-button>
			</div>
	</div>
</el-dialog>
</div>
</template>

<script>
// self
import exaType from './exaPlanType.js'
// import country from './country.js'
// import nationality from './nationality.js'
// prop
	import printUtil from "@/untils/printUtil";
	import { Wplan } from "@/assets/printTemplateConfig/Wplan";
// ext
import { getLunar } from 'chinese-lunar-calendar'

// 接口
import { 
	addPurchasingPlan,
	getWare,selectDropDownList,selectInformation,
	getPlan,toExamine
	} from "@/api/PSI.js";
export default {
	props: ['parentMethod'],
	inject: ['reload'], // 无痕刷新
	components:{
		
	},
	data(){
		return{
			//str
			diglogTile:'', // 动态页面的动态标题
			tableWidth:'', //右侧表格动态宽度
			totalAmt:'', //合计金额
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			idx:'',
			//num
			
			//ble
			disabled:true,
			totaldisabled:true,
			exaDialogVisible:false,
			dialogFormVisible:false,
			//arr
			formType:[],
			tableData:[],
			selectOption:[{id:'1',label:'西药库',value:'西药库'}],
			ghdwOption:[],
			nameOption:[],
			tableRows:[
				{ name:"药品名称", prop:"drugName", type:""},{ name:"规格描述", prop:"drugSpec", type:"" },
				{ name:"采购数量", prop:"purCnt", type:"" },{ name:"参考单价", prop:"purcPric", type:"" },
				{ name:"参考售价", prop:"purcPric", type:"" },{ name:"剂量单位", prop:"unt", type:"" },
				{ name:"生产厂家", prop:"prodentpName", type:"" },{ name:"供货单位", prop:"supplyCandidateName", type:"" },
				// { name:"合同数量", prop:"gdTime", type:"" },{ name:"已购数量", prop:"zf", type:"" },{ name:"库存数量", prop:"ph", type:"" },
				// { name:"近期销量", prop:"scrq", type:"" }
			],
			//obj
			lists:{
				id:'',
				manufacturerName:'', //生产厂家名称
				clinicId:'', //诊所序号
				docId:'', //采购计划表id
				drugId:'', //药品id
				prodentpNameId:'', //生成厂家序号
				purCnt:'', //采购数量
				purcAmt:'', //参考金额
				purcPric:'', //参考单价
				remarks:'', //备注
				stockCnt:'', //库存数量
				supplyCandidateName:'', //供货单位名称
				unt:'', //剂量单位
			},
			addForm:{
				applicantId:'',//申请人Id
				busDate:'', //业务日期
				clinicId:'', //诊所ID
				createId:'', //制单人序号
				createTime:'', //制单时间
				docNum: '', //单据编号
				nullifyId:'',//作废人
				nullifyTime:'', //作废时间
				passingOrdersId:'', //过单人
				passingOrdersTime:'', // 过单时间
				putInDep: "",//申请科室序号
				remarks: "",//备注
				reviewId:'', //审核人
				reviewTime:'', //审核时间
				state:'', //单据状态
				supplyCandidateName:'', //供货单位
				supplyCandidateId:'', //供货单位序号
				terminalId:'', //终端序号
				totalAmt:'', //合计金额
				drugName:'', //药品名称
				drugSpecifications:'', //规格描述
				manufacturerName:'', //生产厂家名称
				//zdy
				purCnt:'', //list下的采购数量
				purcPric:'', //list下的单价金额
				//2
				list:[],
			},
			options:[],
			ssrOption:[],
			gysOption:[],
		}
	},
	mounted() {
		// 左侧提交表单
		this.formType = exaType.map(function(val) {
			return val
		})
		//获取动态盒子宽度，实时赋值给右侧
		this.$nextTick(() => {
		    const box = this.$refs.myBox;
		    this.tableWidth = box.offsetWidth - 288;
		    console.log('盒子的宽度是:', this.tableWidth);
		});
		this.addForm.busDate = new Intl.DateTimeFormat('zh-CN').format(new Date());
		
	},
	methods:{
		// 打开model 获取采购计划数据
		async openModel(parm){
			this.diglogTile = parm.name
			console.log(this.diglogTile);
			this.exaDialogVisible = true;
			let res = await getPlan({id:parm.id})
			console.log(res,'获取采购计划');
			this.addForm = res.data
			this.totalAmt = res.data.totalAmt
			this.tableData = res.data.list
			
			// if(parm.name.includes('打印')){
			// 	printUtil.init(Wplan)
			// 	printUtil.print(this.planMedicalRecord());
			// }
		},
		// 时间处理
		changDate(val){
			let i = this.idx
			switch(i) {
				case 5:
				function formatDate(date) {
				  const year = date.getFullYear();
				  const month = (date.getMonth() + 1).toString().padStart(2, '0');
				  const day = date.getDate().toString().padStart(2, '0');
				  return `${year}-${month}-${day}`;
				}
				// 使用示例
				const now = new Date();
				this.addForm.busDate = formatDate(val);
			}
		},
		deleteRow(index, rows) {
		  rows.splice(index, 1);
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		// testA(val){
		// 	console.log(val);
		// },
		// 键盘事件
		 handleKeyup(event) {
		  // 检查按键
		  if (event.key === 'Enter') {
			// 执行相应的动作
		  }
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleClose(done) {
			done();
		},
		// 确定提交
		async Submit(){
			this.addForm.state = 2
			let result = await toExamine(this.addForm)
			if (result.code === 200) {
				this.reload(); // 更新数据驱动
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error('审核失败！'+result.message)
			}
		},
		//确定审核
		async exaSubmit(){
			this.addForm.state = 4
			this.addForm.reviewId = JSON.parse(localStorage.getItem('userInfo')).userId;
			let result = await toExamine(this.addForm)
			if (result.code === 200) {
				this.reload(); // 更新数据驱动
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error('审核失败！'+result.message)
			}
		},
		// 拒绝审核
		refuseExamine(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 0
				let result = await toExamine(this.addForm)
				if (result.code === 200) {
					this.reload(); // 更新数据驱动
					this.exaDialogVisible = false;
					this.$message({ type: 'success', message: result.message});
				} else {
					this.$message.error('不准不审核！'+result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		//确定过单
		async passOrderSubmit(){
			this.addForm.state = 5
			this.addForm.passingOrdersId = JSON.parse(localStorage.getItem('userInfo')).userId;
			console.log(this.addForm,'过单数据');
			let result = await toExamine(this.addForm)
			if (result.code === 200) {
				this.$message({ type: 'success', message: result.message});
				this.reload(); // 更新数据驱动
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		// 拒绝过单
		refusePassOrder(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 2
				console.log(this.addForm);
				let result = await toExamine(this.addForm)
				if (result.code === 200) {
					this.reload(); // 更新数据驱动
					this.exaDialogVisible = false;
				} else {
					this.$message.error('不准不过单！'+result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		// 草稿保存
		async draftSubmit(){
			 this.addForm.list.push(this.lists)
			 this.addForm.totalAmt = this.cbValue
			 this.addForm.state = 0
			 console.log(this.addForm);
			 let result = await addPurchasingPlan(this.addForm)
			 if (result.code === 200) {
			 	this.$message({
			 		type: 'success',
			 		message: result.message,
			 	});
			 	this.reload(); // 更新数据驱动
			 	this.exaDialogVisible = false;
			 } else {
			 	this.$message.error(result.message)
			 }
		},
		dy(){
		  const printData = this.planMedicalRecord();
		  console.log('打印数据:', printData); // 调试用
		  printUtil.init(Wplan);
		  printUtil.print(printData);
		},
		// 打印相关
		printMedicalRecord() {
		  // 初始化hiprint打印模板
		  const template = new hiprint.PrintTemplate({
		    template: Wplan, // 使用Wstore模板
		    data: this.planMedicalRecord() // 传入打印数据
		  });
		  
		  // 执行打印
		  template.print();
		},
		previewMedicalRecord() {
		  // 初始化hiprint打印模板
		  const template = new hiprint.PrintTemplate({
		    template: Wplan, // 使用Wstore模板
		    data: this.planMedicalRecord() // 传入打印数据
		  });
		  
		  // 执行预览
		  template.preview();
		},
		planMedicalRecord() {
		  // 准备打印数据
		  const printData = {
		    // 头部信息
		    createTime: this.addForm.passingOrdersTime || new Date().toLocaleString(),
		    docNum: this.addForm.purcInvoCodg || '',
		    supplierName: this.addForm.supplyCandidateName || '',
		    
		    // 表格数据 - 必须与Wstore模板中的字段完全匹配
		    tableData: this.tableData.map((item, index) => ({
		      invyId: index + 1, // 序号
		      drugName: item.drugName || '',
		      drugSpec: item.drugSpec || '',
		      purcCnt: item.purcCnt || 0,
		      pacUnt: item.pacUnt || '', // 单位(修正为pacUnt)
		      purcPric: item.purcPric || 0,
		      purcAmt: (item.purcCnt * item.purcPric) || 0,
		      salePric: item.salePric || 0,
		      saleAmt: (item.purcCnt * item.salePric) || 0,
		      manuLotnum: item.manuLotnum || '', // 生产批号
		      expyDate: item.expyDate || '', // 有效期
		      prodentpName: item.prodentpName || '' // 生产厂家
		    })),
		    
		    // 底部信息
		    costAmt: this.cbValue || this.addForm.totalAmt || 0,
		    saleAmt: this.tableData.reduce((sum, item) => sum + (item.purcCnt * item.salePric), 0) || 0,
		    creater: this.addForm.creater || '未知采购人',
		    reviewer: this.addForm.reviewer || '未知审核人',
		    passOrder: this.addForm.passOrder || '未知过单人',
		    busDate: this.addForm.busDate || new Date().toLocaleString() // 打印时间
		  };
		  
		  return printData;
		},
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.form = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.form);
			this.formdisabled = true
			// this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
			// console.log(this.form.textSpell);
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 20; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 12; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 18;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 数字
			  else if (Number.isFinite(Number(char))) length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
			  // 其他 8px
			  else length += 8;
			}
			return length;
		  }
		},
	},
	
}
</script>

<style lang="less" scoped>
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
	/deep/ .el-dialog__header{
		padding: 4px;
		background-color: #007bb0;
	}
	/deep/ .el-select > .el-input{
		width: 100%;
	}
	/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
		margin-bottom: 8px;
	}
	/deep/ .el-dialog__title{
		font-size: 12px;
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn {
		top: 10px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
		background-color: brown;
	}
	/deep/ .el-dialog__body{
		padding: 8px;
	}
	/deep/ .el-form-item__label{
		display: flex;
		justify-content: right;
		font-size: 12px;
	}
    .addAcc{
		// self
		// 选项卡
		.tabs{

			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				margin-bottom: 8px;
				.a{
					flex: 1;
					display: flex;
					align-items: center;
				}
				.table{
					width: 100%;
					margin-top: 12px;
					/deep/ .el-divider__text{
                        padding: 0 12px;
                    }
					/deep/ .el-table .cell{
						text-align: left;
					}
					/deep/ .el-table th{
						background-color: #f1f1f1;
						border: none;
						color: #2d2d2d;
						font-weight: bold;
						font-size: 12px;
					}
					/deep/ .el-table td.el-table__cell div{
						font-size: 12px;
					}
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>